using System;
using System.Text;
using System.Diagnostics;
using System.Collections.Generic;

namespace My.IdlConverter.Core.Parsers
{
    public class ParameterParser : ParserBase
    {
        public ParameterParser()
            : base()
        {
        }
        ~ParameterParser() { }

        public override object Parse(string target)
        {
            try
            {
                target = target.Trim();
                int prePosOfDefaultValue = target.IndexOf('=');
                bool hasDefaultValue = (prePosOfDefaultValue != -1);
                string defaultValue = "";
                if (hasDefaultValue)
                {
                    defaultValue = target.Substring(prePosOfDefaultValue + 1);
                    defaultValue.Trim();
                    target = target.Substring(0, prePosOfDefaultValue);
                    target = target.Trim();
                }
                int spacePos = target.LastIndexOf(' ');
                string paramType = target;
                string paramName = "";
                if (spacePos != -1)
                {
                    paramType = target.Substring(0, spacePos);
                    paramType = paramType.Trim();
                    paramName = target.Substring(spacePos);
                    paramName = paramName.Trim(' ');
                }

                Types.TypeTranslator typeTranslator = new Types.TypeTranslator(paramType);
                Types.IType type = typeTranslator.Translate();
                Parameter paramObj = new Parameter(type, paramName, defaultValue);
                type.Parent = paramObj;

                Success = true;
                return paramObj;
            }
            catch (Exception e)
            {
                Debug.Assert(false);
                Trace.Write(e.Message);
                return null;
            }
        }
    }
}
